import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/login/login.vue'
import Main from '../views/main/Main.vue'
import Home from '../views/main/Home.vue'
import User from '../views/main/User.vue'
import Search from '../views/Search/Search.vue'
import SearchResult from '../views/Search/SearchResult.vue'
import ArticleDetil from '../views/ArticleDetail/ArticleDetail.vue'
import UserEdit from '../views/UserEdit/UserEdit.vue'
import Chat from '../views/Chat/Chat.vue'
import store from '../store/index'
// 1. 将 VueRouter 本身提供的 $router.push 方法转存到常量中
const originalPush = VueRouter.prototype.push
// 2. 自定义 $router.push 方法，在内部调用原生的 originalPush 方法进行路由跳转；并通过 .catch 捕获错误
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  // 通过 .catch 捕获错误
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

// 清空路由规则
const routes = [
  { path: '/login', component: Login, name: 'login' },
  { path: '/search', component: Search, name: 'search' },
  // 开启成功后可以在其他位置接收
  { path: '/search/:kw', component: SearchResult, name: 'search-result', props: true },
  { path: '/article/:id', component: ArticleDetil, name: 'art-detail', props: true },
  { path: '/user/edit', component: UserEdit, name: 'user-edit' },
  { path: '/chat', component: Chat, name: 'chat' },
  {
    path: '/',
    component: Main,
    // name: 'main',
    children: [
      { path: '', component: Home, name: 'home' },
      { path: '/user', component: User, name: 'user' }

    ]
  }

]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  if (to.path === '/user' || to.path === '/user/edit') {
    const tokenStr = store.state.tokenInfo.token
    if (tokenStr) {
      next()
    } else {
      next(`/login?pre=${to.fullPath}`)
    }
  } else {
    next()
  }
})

export default router
